<template>
  <div class="cart">
    <!-- 顶部导航 -->
    <navbar />
    <van-empty description="没有订单" v-if="cart == []" />
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell v-for="item in cart" :key="item.id">
        <van-row gutter="20" type="flex" align="center">
          <van-col span="4">
            <van-image width="60" height="60" fit="cover" :src="item.image" />
          </van-col>
          <van-col span="10" offset="2">
            <h3>{{ item.title }}</h3>
            <span>¥{{ item.price }}</span>
          </van-col>
          <van-col span="4">x{{ item.count }}</van-col>
          <van-col span="4">
            <van-button
              icon="delete-o"
              type="primary"
              plain
              size="small"
              @click="delItem(item.id)"
            />
          </van-col>
        </van-row>
      </van-cell>
    </van-list>
    <div class="total">
      <span>总金额:¥{{ total }}</span>
      <button @click="settlement">结算</button>
    </div>
    <tabbar />
  </div>
</template>

<script>
import Navbar from "../components/Navbar.vue";
import Tabbar from "../components/Tabbar.vue";
import { Dialog } from "vant";
import { mapState } from "vuex";
import { mapMutations } from "vuex";
export default {
  components: { Navbar, Tabbar },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
    };
  },
  computed: {
    ...mapState(["cart", "isLOgin"]),
    total() {
      let sum = 0;
      if (this.cart != []) {
        this.cart.forEach((item) => {
          sum += item.price * item.count;
        });
      }
      return sum;
    },
  },
  methods: {
    ...mapMutations(["delGoods"]),
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1);
        }

        // 加载状态结束
        this.loading = false;

        // 数据全部加载完成
        if (this.list.length >= 10) {
          this.finished = true;
        }
      }, 1000);
    },
    delItem(id) {
      this.delGoods(id);
    },
    settlement() {
      Dialog.confirm({
        title: "标题",
        message: "弹窗内容",
      })
        .then(() => {
          // on confirm
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>
<style scoped>
.total {
  position: fixed;
  bottom: 50px;
  width: 100%;
  background-color: #fff;
}
.total > span {
  float: left;
  margin-left: 10px;
  line-height: 50px;
}
.total > button {
  float: right;
  display: block;
  width: 80px;
  height: 40px;
  margin: 5px 10px;
  border: 0;
  border-radius: 10px;
  color: #fff;
  background-color: #f00;
}
</style>
